package com.rocketmq.temp3.service.bo;

import com.rocketmq.temp3.common.constant.BizConstant;
import com.rocketmq.temp3.common.shared.BaseResponse;
import com.rocketmq.temp3.common.shared.DataResult;
import com.rocketmq.temp3.common.utils.JacksonUtils;
import com.rocketmq.temp3.entity.po.Product;
import com.rocketmq.temp3.service.bo.base.BaseService;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderService extends BaseService {

    public DataResult<Integer> saveOrder() {
        Long orderId = System.currentTimeMillis();
        Product order = this.createOrder(orderId.intValue());
        String msg = JacksonUtils.to(order);

        Message<String> message = MessageBuilder
                .withPayload(msg)
                .setHeader("msg", msg)
                .build();
        // 该消息不允许被消费者消费
        rocketMQTemplate.sendMessageInTransaction("mq-producer-group", "sm-platform-topic", message, null);

        return BaseResponse.success(BizConstant.ResultCode.SUCCESS, orderId.intValue());
    }

    private Product createOrder(Integer orderId) {
        List<Product> products = productBaseDao.selectAll();
        Product product = products.get(19);
        product.setProductId(orderId);
        return product;
    }

}
